<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item label="申报阶段" prop="state">
				<el-select v-model="state.queryForm.applyStage" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyStage" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申报状态" prop="status">
				<el-select v-model="state.queryForm.applyStatus" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyStatus" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="审核结论" prop="conclusion">
				<el-select v-model="state.queryForm.auditResult" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in applyResult" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="类别" prop="category">
				<el-select v-model="state.queryForm.standardCategory" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in standardCategory" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="项目名称" value="1" />
							<el-option label="主编单位" value="2" />
							<el-option label="主管单位" value="3" />
							<el-option label="联系人" value="4" />
							<el-option label="申请年份" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="类型" prop="standardType">
				<el-select v-model="state.queryForm.standardType" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in standardType" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item v-auth="'M001_Submit'">
				<el-button type="primary" :disabled="!hasPermission" @click="submitHandle()">提交</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_Upload'">
				<el-button type="primary" :disabled="!hasPermission" @click="uploadFileHandle()">文件上传</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_Export'">
				<el-button type="primary" @click="exportHandle()">项目导出</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_Cancel'">
				<el-button type="primary" @click="revokeHandle()">撤销项目</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_CancelPublish'">
				<el-button type="primary" :disabled="!hasPublish" @click="cancleReleaseHandle()">取消发布</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_RePublish'">
				<el-button type="primary" :disabled="!hasUnPublish" @click="republishHandle()">重新发布</el-button>
			</el-form-item>
		</el-form>
		<el-table ref="multipleTableRef" v-loading="state.dataListLoading" :data="dataList" stripe border @selection-change="selectionChangeHandle">
			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" />
			<el-table-column prop="index" label="序号" header-align="center" align="center" width="60" fixed="left"></el-table-column>
			<el-table-column
				prop="standardProjectName"
				label="申报项目"
				header-align="center"
				align="center"
				width="220"
				fixed="left"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center" width="220" resizable sortable></el-table-column>
			<el-table-column prop="contacts" label="联系人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column
				prop="projectFunding"
				label="申请经费(万元)"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="applyYear" label="申报年度" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="applyStage" label="申报阶段" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T001', scope.row.applyStage) }}</span>
					<!-- <span v-if="scope.row.applyStage == 6">住建委审核</span> -->
				</template>
			</el-table-column>
			<el-table-column prop="applyStatus" label="申报状态" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T004', scope.row.applyStatus) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="主管部门(提出单位)审核" header-align="center" align="center" prop="auditResult" min-width="170">
				<template v-if="userStore.user.roleCode.includes('SHZG')" #default="scope">
					<el-radio-group v-if="scope.row.auditResultF && scope.row.permission != 1" v-model="scope.row.auditResultF" disabled>
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
					<el-radio-group v-if="scope.row.applyStage == 1 && scope.row.permission == 1" v-model="scope.row.status">
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
				</template>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultF"
					label="主管部门1"
					width="170"
					header-align="center"
					align="center"
				>
					<template #default="scope">
						<el-radio-group v-if="scope.row.auditResultF" v-model="scope.row.auditResultF" disabled>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
						<el-radio-group
							v-if="scope.row.applyStage == 1 && scope.row.permission == 1 && scope.row.auditResultF == null"
							v-model="scope.row.status"
						>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultS"
					label="主管部门2"
					width="170"
					header-align="center"
					align="center"
				>
					<template #default="scope">
						<el-radio-group v-if="scope.row.auditResultS" v-model="scope.row.auditResultS" disabled>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
						<el-radio-group
							v-if="scope.row.applyStage == 1 && scope.row.permission == 1 && scope.row.auditResultS == null && scope.row.auditResultF"
							v-model="scope.row.status"
						>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultT"
					label="主管部门3"
					width="170"
					header-align="center"
					align="center"
				>
					<template #default="scope">
						<el-radio-group v-if="scope.row.auditResultT" v-model="scope.row.auditResultT" disabled>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
						<el-radio-group
							v-if="scope.row.applyStage == 1 && scope.row.permission == 1 && scope.row.auditResultT == null && scope.row.auditResultS"
							v-model="scope.row.status"
						>
							<el-radio value="2" size="large">推荐</el-radio>
							<el-radio value="3" size="large">不推荐</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultPro"
				label="项目汇总"
				header-align="center"
				align="center"
				width="170"
			>
				<template #default="scope">
					<el-radio-group v-if="scope.row.applyStage > 1 && scope.row.auditResultPro != null" v-model="scope.row.auditResultPro" disabled>
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
					<el-radio-group v-if="scope.row.applyStage == 2 && scope.row.permission == 1" v-model="scope.row.status">
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultExp"
				label="专家评审"
				header-align="center"
				align="center"
				width="170"
			>
				<template #default="scope">
					<el-radio-group v-if="scope.row.applyStage > 2 && scope.row.auditResultExp != null" v-model="scope.row.auditResultExp" disabled>
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
					<el-radio-group v-if="scope.row.applyStage == 3 && scope.row.permission == 1" v-model="scope.row.status">
						<el-radio value="2" size="large">推荐</el-radio>
						<el-radio value="3" size="large">不推荐</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultCen"
				label="总站审核"
				header-align="center"
				align="center"
				width="190"
			>
				<template #default="scope">
					<el-radio-group v-if="scope.row.applyStage > 3 && scope.row.auditResultCen != null" v-model="scope.row.auditResultCen" disabled>
						<el-radio value="4" size="large">拟立项</el-radio>
						<el-radio value="5" size="large">拟不立项</el-radio>
					</el-radio-group>
					<el-radio-group v-if="scope.row.applyStage == 4 && scope.row.permission == 1" v-model="scope.row.status">
						<el-radio value="4" size="large">拟立项</el-radio>
						<el-radio value="5" size="large">拟不立项</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultCom"
				label="住建委审核"
				header-align="center"
				align="center"
				width="170"
			>
				<template #default="scope">
					<el-radio-group v-if="scope.row.applyStage > 4 && scope.row.auditResultCom != null" v-model="scope.row.auditResultCom" disabled>
						<el-radio value="6" size="large">立项</el-radio>
						<el-radio value="7" size="large">不立项</el-radio>
					</el-radio-group>
					<el-radio-group v-if="scope.row.applyStage == 5 && scope.row.permission == 1" v-model="scope.row.status">
						<el-radio value="6" size="large">立项</el-radio>
						<el-radio value="7" size="large">不立项</el-radio>
					</el-radio-group>
				</template>
			</el-table-column>
			<el-table-column prop="projectDocument" label="批文" header-align="center" align="center" width="200">
				<template #default="scope">
					<div v-if="scope.row.applyStatus != '4'">
						<span
							v-for="item in scope.row.projectDocument"
							:key="item.id"
							type="success"
							style="margin-left: 5px; cursor: pointer; text-decoration: underline"
							@click="handleUploadPdfPreview(item)"
						>
							{{ item.fileRealName }}.{{ item.fileExtName }}
						</span>
					</div>
					<div v-else></div>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="110">
				<template #default="scope">
					<el-icon
						v-if="scope.row.applyStage > 1 && scope.row.applyStage < 6 && !userStore.user.roleCode.includes('SHZG')"
						v-auth="'M001_U2'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="handleEdit(scope.row)"
					>
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handleView(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="(scope.row.permission == '1' || scope.row.permission == '2') && scope.row.applyStatus != '3'"
						:size="16"
						color="#1491FF"
						title="审核附件及意见上传"
						style="cursor: pointer; margin: 0 6px"
						@click="toComment(scope.row)"
					>
						<ChatLineSquare />
					</el-icon>
					<el-icon
						v-if="scope.row.permission == 1 && scope.row.applyStage == 1"
						:size="16"
						color="#1491FF"
						title="退回"
						style="cursor: pointer; margin: 0 6px"
						@click="handleReturnBack(scope.row)"
					>
						<CircleClose />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<!-- <cmDialog v-model="optionsShowDialog" modal-title="意见" model-width="500px">
			<el-form ref="optionsFormRef" :model="optionsInfo" :rules="optionRules" label-width="120px">
				<el-row>
                    <el-form-item label="主管部门名称" style="width: 100%;">
                        {{userStore.user.orgName}}
                    </el-form-item>
                </el-row>
				<el-row>
					<el-form-item label="对申报标准意见" style="width: 100%" prop="opinions">
						<el-input v-model="optionsInfo.opinions" type="textarea" :rows="3" style="width: 100%"></el-input>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="审批附件(pdf)" style="width: 100%">
						<el-upload
							ref="uploadPdfRef"
							drag
							:action="uploadApi"
							:headers="uploadHeaders"
							:data="uploadData"
							accept=".pdf"
							:on-success="handleUploadSuccess"
							:on-remove="handleUploadRemove"
						>
							<el-icon class="el-icon--upload"><upload-filled /></el-icon>
							<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						</el-upload>
					</el-form-item>
				</el-row>
			</el-form>
			<div class="dialog-foot">
				<el-button @click="optionsShowDialog = false">取消</el-button>
				<el-button type="primary" @click="handleOptionSubmit(optionsFormRef)">确定</el-button>
			</div>
		</cmDialog> -->
		<addDialog
			v-model="showAddDialog"
			:edit-id="editId"
			:is-view="isView"
			:is-audit="isAudit"
			:show-audit="true"
			@submit-success="addSuccess"
		></addDialog>
		<cmDialog v-model="showUploadDialog" modal-title="审核附件及意见上传" :model-width="showUploadType == 1 ? '600px' : '1200px'">
			<el-form ref="optionsFormRef" label-width="120px" :rules="optionRules" :model="optionsInfo">
				<el-form-item v-if="showUploadType == 1" label="意见附件类型" style="width: 100%">
					<el-radio-group v-model="optionsInfo.stage" @change="uploadTypeChange">
						<el-radio v-for="(item, index) in optionsList" :key="index" :value="item.value" size="large">{{ item.name }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<!-- <el-row v-if="optionsInfo.stage == currentStage && currentPermission == '1'"> -->
				<el-row v-if="currentPermission == '1'">
					<el-form-item label="对申报标准意见" style="width: 100%" prop="opinions">
						<el-input
							v-model="optionsInfo.opinions"
							type="textarea"
							:rows="3"
							placeholder="请输入"
							style="width: 100%"
							maxlength="500"
							show-word-limit
						></el-input>
					</el-form-item>
				</el-row>
				<el-form-item :label="optionsInfo.stage == '4' ? '签报等资料' : '附件(pdf)'" style="width: 100%" prop="filesRecordList">
					<el-upload
						ref="uploadPdfRef"
						drag
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData"
						accept=".pdf"
						:on-success="handleUploadSuccess"
						:on-remove="handleUploadRemove"
						:on-preview="handleUploadPdfPreview"
						:file-list="optionsInfo.filesRecordList"
						:before-upload="beforeUploadPdf"
						:on-change="handleChange"
					>
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-row v-if="currentStage == '5' || isRepublish">
					<el-form-item label="批文年度" prop="approvalFileYear">
						<el-date-picker
							v-model="optionsInfo.approvalFileYear"
							type="year"
							format="YYYY"
							value-format="YYYY"
							placeholder="选择年份"
							style="width: 240px"
						/>
					</el-form-item>
					<el-form-item label="文号" prop="approvalFileNumber">
						<el-input v-model="optionsInfo.approvalFileNumber" type="number" placeholder="请输入" style="width: 240px" />
					</el-form-item>
				</el-row>
			</el-form>
			<div v-if="showUploadType == 2" style="display: flex; justify-content: flex-end; padding-bottom: 10px">
				<el-button type="primary" size="small" @click="exportHandle2">导出</el-button>
			</div>
			<el-table v-if="showUploadType == 2" :data="selectList" border size="small">
				<el-table-column label="序号" type="index" width="50" align="center" />
				<el-table-column label="项目名称" header-align="center" align="center" prop="standardProjectName" />
				<el-table-column label="主编单位" header-align="center" align="center" prop="editorUnitName" />
				<el-table-column label="申请经费(万元)" header-align="center" align="center" prop="projectFunding" width="80" />
				<el-table-column label="申请年份" header-align="center" align="center" prop="applyYear" width="70" />
				<el-table-column prop="applyStage" label="申报阶段" header-align="center" align="center" width="100">
					<template #default="scope">
						<span>{{ dictionaryStore.getDictionaryName('T001', scope.row.applyStage) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="主管部门审核" header-align="center" align="center" prop="auditResult">
					<el-table-column prop="auditResultF" label="主管部门1" width="80" header-align="center" align="center">
						<template #default="scope">
							<div v-if="scope.row.auditResultF == 2">推荐</div>
							<div v-if="scope.row.auditResultF == 3">不推荐</div>
						</template>
					</el-table-column>
					<el-table-column prop="auditResultS" label="主管部门2" width="80" header-align="center" align="center">
						<template #default="scope">
							<div v-if="scope.row.auditResultS == 2">推荐</div>
							<div v-if="scope.row.auditResultS == 3">不推荐</div>
						</template>
					</el-table-column>
					<el-table-column prop="auditResultT" label="主管部门3" width="80" header-align="center" align="center">
						<template #default="scope">
							<div v-if="scope.row.auditResultT == 2">推荐</div>
							<div v-if="scope.row.auditResultT == 3">不推荐</div>
						</template>
					</el-table-column>
				</el-table-column>
				<el-table-column prop="auditResultPro" label="项目汇总" header-align="center" align="center" width="80">
					<template #default="scope">
						<div v-if="scope.row.auditResultPro == 2">汇总推荐</div>
						<div v-if="scope.row.auditResultPro == 3">汇总不推荐</div>
					</template>
				</el-table-column>
				<el-table-column prop="auditResultExp" label="专家评审" header-align="center" align="center" width="80">
					<template #default="scope">
						<div v-if="scope.row.auditResultExp == 2">专家推荐</div>
						<div v-if="scope.row.auditResultExp == 3">专家不推荐</div>
					</template>
				</el-table-column>
				<el-table-column prop="auditResultCen" label="总站审核" header-align="center" align="center" width="80">
					<template #default="scope">
						<div v-if="scope.row.auditResultCen == 4">拟立项</div>
						<div v-if="scope.row.auditResultCen == 5">拟不立项</div>
					</template>
				</el-table-column>
				<el-table-column prop="auditResultCom" label="住建委审核" header-align="center" align="center" width="80">
					<template #default="scope">
						<div v-if="scope.row.auditResultCom == 6">立项</div>
						<div v-if="scope.row.auditResultCom == 7">不立项</div>
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<div class="dialog-foot" style="padding-bottom: 12px">
					<el-button @click="showUploadDialog = false">取消</el-button>
					<el-button type="primary" :disabled="uploadLoading" @click="handleUploadSubmit(optionsFormRef)">确定</el-button>
				</div>
			</template>
		</cmDialog>
		<cmDialog v-model="showReturnDialog" modal-title="退回项目" model-width="600px">
			<el-form label-width="120px">
				<el-form-item label="退回理由" style="width: 100%">
					<el-input v-model="returnBackInfo.remark" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-foot" style="padding-bottom: 12px">
					<el-button @click="showReturnDialog = false">取消</el-button>
					<el-button type="primary" @click="handleReturnBackSubmit">确定</el-button>
				</div>
			</template>
		</cmDialog>
	</el-card>
</template>
<script setup lang="ts">
import {
	addAuditOptions,
	batchAudit,
	batchAuditFiles,
	cancelProject,
	getAuditOptions,
	getList,
	getStage,
	republishProject,
	returnProject,
	revokeProject
} from '@/api/declare/audit'
import { filePreviewByName } from '@/api/sys/upload'
import cmDialog from '@/components/cm-dialog/index.vue'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import type { FormInstance, TableInstance, UploadInstance, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from '../declare/components/addDialog.vue'
const route = useRoute()
const pendingStatus = route.query.pendingStatus

const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()

const applyStage = dictionaryStore.getDictionaryByCode('T001')
const applyStatus = dictionaryStore.getDictionaryByCode('T004')
const applyResult = dictionaryStore.getDictionaryByCode('T013')
const standardCategory = dictionaryStore.getDictionaryByCode('T005')
const standardType = dictionaryStore.getDictionaryByCode('T006')

const state = reactive({
	queryForm: {
		applyStage: null,
		applyStatus: null,
		auditResult: null,
		standardCategory: null,
		standardType: null,
		standardProjectName: null,
		editorUnitName: null,
		responsibleOrgName: null,
		contactName: null,
		applyYear: null,
		responsiblePerson: null,
		mainDrafterName: null,
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null
})

interface IListDataType {
	index: number
	applyResult: string
	applyStage: string
	applyStatus: string
	applyYear: string
	contacts: string
	editorUnitName: string
	id: string
	opinions: null
	permission: null
	projectFunding: number
	responsibleOrgName: string
	standardProjectName: string
}

const statusMap = {
	'1': '未处理',
	'2': '推荐',
	'3': '不推荐',
	'4': '拟立项',
	'5': '拟不立项',
	'6': '立项',
	'7': '不立项',
	'8': '退回'
}
const codeMap = {
	'1': 'ZGBM_Approve',
	'2': 'XMHZ_Approve',
	'3': 'ZJPS_Approve',
	'4': 'ZZSH_Approve',
	'5': 'ZJWSH_Approve'
}

const multipleTableRef = ref<TableInstance>()
const dataList = ref<IListDataType[]>([])
const optionsShowDialog = ref(false)
const optionsFormRef = ref<FormInstance>()
const optionsInfo = ref({
	id: '',
	opinions: '',
	stage: '',
	filesRecordList: [],
	approvalFileYear: '',
	approvalFileNumber: ''
})
const currentStage = ref('')
const currentPermission = ref('')
const optionsList = ref([])
const optionRules = computed(() => ({
	opinions: showUploadType.value == 1 ? [{ required: true, message: '请输入意见', trigger: 'blur' }] : [],
	filesRecordList: [
		{
			required: true,
			validator: (rule, value, callback) => {
				if (value && value.length > 0) {
					callback() // 验证通过
				} else {
					callback(new Error('请上传文件')) // 验证失败
				}
			}
		}
	],
	approvalFileYear: [{ required: true, message: '请选择年份', trigger: 'blur' }],
	approvalFileNumber: [{ required: true, message: '请输入文号', trigger: 'blur' }]
}))
const uploadPdfRef = ref<UploadInstance>()
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = ref({
	extCode: '',
	remark: '审批附件(pdf)'
})
const uploadList = ref([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const isAudit = ref<boolean>(false)
const selectList = ref([])
const showUploadDialog = ref(false)
const showUploadType = ref(1)
const showReturnDialog = ref<boolean>(false)
const returnBackInfo = ref({
	id: '',
	codeType: 'StandardApply',
	remark: ''
})

const uploadLoading = ref(false)
const isRepublish = ref(false)

const hasPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.permission == 1)
	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

const hasPublish = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.applyStatus == 3)

	return allPermissionValid
})

const hasUnPublish = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.applyStatus == 4)

	return allPermissionValid
})

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			isView.value = false
			isAudit.value = false
		}
	}
)

watch(
	() => optionsShowDialog.value,
	newVal => {
		if (newVal == false) {
			uploadList.value = []
			uploadPdfRef.value.clearFiles()
			optionsFormRef.value.clearValidate()
		}
	}
)

watch(
	() => showUploadDialog.value,
	newVal => {
		if (newVal == false) {
			uploadList.value = []
			uploadPdfRef.value.clearFiles()
			selectList.value = []
			isRepublish.value = false
			optionsFormRef.value.clearValidate()
			optionsFormRef.value.resetFields()
			// uploadType.value = null
		}
	}
)

watch(
	() => showReturnDialog.value,
	newVal => {
		if (newVal == false) {
			returnBackInfo.value = {
				id: '',
				codeType: 'StandardApply',
				remark: ''
			}
		}
	}
)

const checkSelectable = (row, index) => {
	return row.permission == 1
}

const getDataList = () => {
	state.queryForm.standardProjectName = ''
	state.queryForm.editorUnitName = ''
	state.queryForm.responsibleOrgName = ''
	state.queryForm.contactName = ''
	state.queryForm.applyYear = ''
	if (state.keyword && !state.keyType) {
		ElMessage.error('请选择关键词类型')
		return
	}
	switch (state.keyType) {
		case '1':
			state.queryForm.standardProjectName = state.keyword
			break
		case '2':
			state.queryForm.editorUnitName = state.keyword
			break
		case '3':
			state.queryForm.responsibleOrgName = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
		case '5':
			state.queryForm.applyYear = state.keyword
			break
	}
	state.dataListLoading = true
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		const list = res.data.list
		state.dataListLoading = false
		dataList.value = []
		if (list.length > 0) {
			list.forEach((item, index) => {
				dataList.value.push({
					index: index + 1,
					...item
				})
			})
		}
		state.total = res.data.total || 0
	})
}

const submitHandle = async () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		const unprocessedIndices = []
		selectedRows.forEach((row, index) => {
			if (!row.status) {
				if (!row.status) {
					unprocessedIndices.push(row.index)
				}
			}
		})
		if (unprocessedIndices.length > 0) {
			throw new Error(`序号为${unprocessedIndices.join('、')}的数据未处理，请检查！`)
		}
		if (selectedRows[0].applyStage != '4') {
			for (const row of selectedRows) {
				const isValid = await checkProjectStatus(row)
				if (!isValid) {
					throw new Error(`序号为${row.index}的项目未上传附件，请检查！`)
				}
			}
		}

		const tableList = []
		selectedRows.forEach(row => {
			tableList.push({
				id: row.id,
				status: row.status,
				remark: statusMap[row.status]
			})
		})
		batchAudit({ tableList: tableList }).then(() => {
			ElMessage.success('操作成功')
			getDataList()
		})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const checkProjectStatus = async project => {
	// 这里替换为实际的异步请求逻辑
	return new Promise(resolve => {
		getAuditOptions({
			id: project.id,
			stage: project.applyStage
		}).then(res => {
			resolve(res.data.filesRecordList.length > 0)
		})
	})
}

const handleUploadSuccess = (res: any, uploadFile: any) => {
	uploadLoading.value = false
	if (res.code == '200') {
		uploadList.value.push(res.data)
		optionsFormRef.value.clearValidate('filesRecordList')
	}
}

const handleUploadRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadList.value = uploadList.value.filter((item: any) => item.id !== id)
	optionsInfo.value.filesRecordList = optionsInfo.value.filesRecordList.filter((item: any) => item.id !== id)
}

const handleChange = (file: UploadRawFile, fileList: any) => {
	optionsInfo.value.filesRecordList = []
	fileList.forEach((file: any) => {
		if (file.response) {
			optionsInfo.value.filesRecordList.push(file.response.data)
		} else {
			optionsInfo.value.filesRecordList.push(file)
		}
	})
	optionsInfo.value.filesRecordList.forEach((file: any) => {
		file.name = file.fileRealName
	})
}

const beforeUploadPdf = (file: UploadRawFile) => {
	const allowedTypes = ['application/pdf']
	const fileExtension = file.name.split('.').pop()?.toLowerCase()
	if (!allowedTypes.includes(file.type) || fileExtension !== 'pdf') {
		ElMessage.error('仅支持上传 PDF 文件')
		return false
	}
	uploadLoading.value = true
	return true
}

const toComment = async row => {
	showUploadDialog.value = true
	showUploadType.value = 1
	currentPermission.value = row.permission
	selectList.value = [row]
	optionsInfo.value.id = row.id
	await getCurrentStage(row.id)
	await getComment()
}

const getComment = async () => {
	await getAuditOptions({
		id: optionsInfo.value.id,
		stage: optionsInfo.value.stage
	}).then(res => {
		optionsInfo.value.opinions = res.data.opinions || ''
		optionsInfo.value.approvalFileYear = res.data.approvalFileYear ? res.data.approvalFileYear.toString() : ''
		optionsInfo.value.approvalFileNumber = res.data.approvalFileNumber || ''
		uploadList.value = res.data.filesRecordList || []
		let fileList = JSON.parse(JSON.stringify(uploadList.value))
		fileList.forEach((file: any) => {
			file.name = file.fileRealName
		})
		optionsInfo.value.filesRecordList = fileList
	})
}

const getCurrentStage = async (id: string) => {
	await getStage({
		id: id
	}).then(res => {
		const nodeList = res.data[0].nodeList
		optionsList.value = nodeList
		currentStage.value = res.data[0].stage.toString()
		optionsInfo.value.stage = JSON.parse(JSON.stringify(currentStage.value))
		uploadData.value.extCode = codeMap[currentStage.value]
	})
}

const handleOptionSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (uploadList.value.length > 0) {
				optionsInfo.value.filesRecordList = uploadList.value
			}
			addAuditOptions(optionsInfo.value).then(() => {
				optionsShowDialog.value = false
				ElMessage.success('审核意见提交成功')
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}

const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	reset()
}

const handleView = (row: any) => {
	isView.value = true
	editId.value = row.id
	isAudit.value = false
	showAddDialog.value = true
}

const handleEdit = (row: any) => {
	editId.value = row.id
	isView.value = false
	isAudit.value = true
	showAddDialog.value = true
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.auditResult = null
	state.queryForm.applyStage = null
	state.queryForm.applyStatus = null
	state.queryForm.standardCategory = null
	state.queryForm.standardType = null
	state.queryForm.standardProjectName = null
	state.queryForm.editorUnitName = null
	state.queryForm.responsibleOrgName = null
	state.queryForm.contactName = null
	state.queryForm.applyYear = null
	state.queryForm.pendingStatus = null
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

const uploadFileHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		selectList.value = selectedRows
		showUploadDialog.value = true
		showUploadType.value = 2
		currentStage.value = selectedRows[0].applyStage
		uploadData.value.extCode = codeMap[selectedRows[0].applyStage]
		optionsInfo.value.id = selectedRows[0].id
		optionsInfo.value.stage = selectedRows[0].applyStage
		getComment()
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const uploadTypeChange = () => {
	uploadData.value.extCode = codeMap[optionsInfo.value.stage]
	getComment()
}

const handleUploadSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	console.log('optionsInfo.value', optionsInfo.value)
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (showUploadType.value == 1) {
				// if (currentStage.value == optionsInfo.value.stage && currentPermission.value == '1') {
				// 	if (optionsInfo.value.opinions == '') {
				// 		ElMessage.error('请输入申报标准意见')
				// 		return
				// 	}
				// } else {
				// 	if (uploadList.value.length == 0) {
				// 		ElMessage.error('未上传文件，请上传文件')
				// 		return
				// 	}
				// }
				let fileList = []
				uploadList.value.forEach((file: any) => {
					fileList.push({
						extCode: file.extCode,
						fileExtName: file.fileExtName,
						filePath: file.filePath,
						fileRealName: file.fileRealName,
						fileSize: file.fileSize,
						id: file.id,
						remark: file.remark,
						systemFileName: file.systemFileName
					})
				})
				addAuditOptions({
					id: optionsInfo.value.id,
					stage: optionsInfo.value.stage,
					opinions: optionsInfo.value.opinions,
					filesRecordList: fileList,
					approvalFileYear: optionsInfo.value.approvalFileYear,
					approvalFileNumber: optionsInfo.value.approvalFileNumber
				}).then(() => {
					ElMessage.success('处理成功')
					showUploadDialog.value = false
				})
			} else {
				// if (uploadList.value.length == 0) {
				// 	ElMessage.error('未上传文件，请上传文件')
				// 	return
				// }
				const ids = selectList.value.map(item => {
					return item.id
				})
				const api = isRepublish.value ? republishProject : batchAuditFiles
				let fileList = []
				uploadList.value.forEach((file: any) => {
					fileList.push({
						extCode: file.extCode,
						fileExtName: file.fileExtName,
						filePath: file.filePath,
						fileRealName: file.fileRealName,
						fileSize: file.fileSize,
						id: file.id,
						remark: file.remark,
						systemFileName: file.systemFileName
					})
				})
				api({
					ids: ids,
					opinions: optionsInfo.value.opinions,
					filesRecordList: fileList,
					approvalFileYear: optionsInfo.value.approvalFileYear,
					approvalFileNumber: optionsInfo.value.approvalFileNumber
				}).then(() => {
					ElMessage.success('处理成功')
					if (isRepublish.value) {
						getDataList()
					}
					showUploadDialog.value = false
				})
			}
		} else {
			console.log('error submit!', fields)
		}
	})
}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		const param = {
			// ids: ids,
			...state.queryForm
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/standardProject/export',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '标准项目导出文件.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const exportHandle2 = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		const ids = selectList.value.map(item => {
			return item.id
		})
		const param = {
			ids: ids
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/standardProject/export',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '标准项目导出文件.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const republishHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		isRepublish.value = true
		selectList.value = selectedRows
		showUploadDialog.value = true
		showUploadType.value = 2
		uploadData.value.extCode = 'ZJWSH_Approve'
		optionsInfo.value.id = selectedRows[0].id
		optionsInfo.value.stage = selectedRows[0].applyStage
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const revokeHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('只能选择一个项目')
		}
		ElMessageBox.confirm(`确定撤销该项目吗？`, '温馨提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				revokeProject({
					id: selectedRows[0].id
				}).then(() => {
					ElMessage.success('操作成功')
					getDataList()
				})
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}
const cancleReleaseHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		if (selectedRows.length > 1) {
			throw new Error('只能选择一个项目')
		}
		ElMessageBox.confirm(`确定取消发布该项目吗？`, '温馨提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				cancelProject({
					id: selectedRows[0].id
				}).then(() => {
					ElMessage.success('操作成功')
					getDataList()
				})
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}
const handleReturnBack = (item: any) => {
	showReturnDialog.value = true
	returnBackInfo.value.id = item.id
}

const handleReturnBackSubmit = () => {
	if (returnBackInfo.value.remark == '') {
		ElMessage.error('退回原因不能为空')
		return
	}
	returnProject(returnBackInfo.value).then(() => {
		ElMessage.success('操作成功')
		showReturnDialog.value = false
		getDataList()
	})
}
const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

onMounted(() => {
	getDataList()
})
</script>
<style lang="scss" scoped>
.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}

.anniu .el-form-item {
	margin-right: 10px !important;
}
</style>
